<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="红包配置">
        1.根据业务需求配置不同档位的红包奖励，<i style="color: red"
          >每个档位红包都设有累充金额限制和角色等级限制项，如无限制请填0</i
        ><br />
        2.设置完成的项目，<i style="color: red">根据业务需要请勾选开启</i>
      </n-card>
    </div>
    <n-card :bordered="false" class="mt-4 proCard">
      <div class="BasicForm">
        <!--      <n-grid cols="1 2xl:1 m:3 l:3 xl:3 2xl:3" responsive="screen">-->
        <!--        <n-grid-item offset="0 s:0 m:1 l:1 xl:1 2xl:1">-->
        <n-form ref="formRef" :model="model">
          <n-dynamic-input
            v-model:value="model.dynamicInputValue"
            #="{ index, value }"
            :on-create="onCreate"
            item-style="margin-bottom: 0;"
            show-sort-button
          >
            <div style="display: flex">
              <!--
                通常，path 的变化会导致 form-item 验证内容或规则的改变，所以 naive-ui 会清理掉
                表项已有的验证信息。但是这个例子是个特殊情况，我们明确的知道，path 的改变不会导致
                form-item 验证内容和规则的变化，所以就 ignore-path-change
              -->
              <n-checkbox
                v-model:checked="value.isCheck"
                style="margin-right: 12px; margin-top: 32px"
              />

              <n-form-item
                :path="`dynamicInputValue[${index}].name`"
                :rule="dynamicNameRule"
                :show-label="true"
                ignore-path-change
                key-field="name"
                label="红包名称:"
              >
                <n-input
                  v-model:value="model.dynamicInputValue[index].name"
                  placeholder="红包名称"
                  @keydown.enter.prevent
                />
                <!--
                  由于在 input 元素里按回车会导致 form 里面的 button 被点击，所以阻止了默认行为
                -->
              </n-form-item>
              <div style="height: 34px; line-height: 34px; margin: 0 8px"></div>
              <n-form-item
                :path="`dynamicInputValue[${index}].money`"
                :rule="dynamicMoneyRule"
                :show-label="true"
                ignore-path-change
                key-field="money"
                label="金额:"
              >
                <n-input
                  v-model:value="model.dynamicInputValue[index].money"
                  placeholder="金额"
                  type="number"
                  @keydown.enter.prevent
                />
              </n-form-item>
              <div style="height: 34px; line-height: 34px; margin: 0 8px"></div>
              <n-form-item
                :path="`dynamicInputValue[${index}].totalRecharge`"
                :rule="dynamicMoneyRule"
                :show-label="true"
                ignore-path-change
                key-field="totalRecharge"
                label="累充金额限制:"
              >
                <n-input
                  v-model:value="model.dynamicInputValue[index].totalRecharge"
                  placeholder="累充金额限制"
                  type="number"
                  @keydown.enter.prevent
                />
              </n-form-item>
              <div style="height: 34px; line-height: 34px; margin: 0 8px"></div>
              <n-form-item
                :path="`dynamicInputValue[${index}].registTime`"
                :rule="dynamicRoleLevelRule"
                :show-label="true"
                ignore-path-change
                key-field="registTime"
                label="注册天数限制:"
              >
                <n-input
                  v-model:value="model.dynamicInputValue[index].registTime"
                  placeholder="注册天数限制"
                  type="number"
                  @keydown.enter.prevent
                />
              </n-form-item>
              <div style="height: 34px; line-height: 34px; margin: 0 8px"></div>
              <n-form-item
                :path="`dynamicInputValue[${index}].roleLevel`"
                :rule="dynamicRoleLevelRule"
                :show-label="true"
                ignore-path-change
                key-field="roleLevel"
                label="角色等级限制:"
              >
                <n-input
                  v-model:value="model.dynamicInputValue[index].roleLevel"
                  placeholder="角色等级限制"
                  type="number"
                  @keydown.enter.prevent
                />
              </n-form-item>
            </div>
          </n-dynamic-input>
          <div>
            <n-space>
              <n-button type="primary" @click="formSubmit">保存</n-button>
            </n-space>
          </div>
        </n-form>
        <!--          <pre>{{ JSON.stringify(model.dynamicInputValue, null, 2) }}</pre>-->
        <!--        </n-grid-item>-->
        <!--      </n-grid>-->
      </div>
    </n-card>
  </div>
</template>

<style>
  .n-dynamic-input .n-dynamic-input-item .n-dynamic-input-item__action {
    margin-top: 25px;
  }
</style>

<style lang="less" scoped>
  .BasicForm {
    width: 1000px;
    margin: 0 auto;
    overflow: hidden;
    padding-top: 20px;
  }
</style>

<script lang="ts" setup>
  import { onMounted, ref } from 'vue';
  import { useMessage } from 'naive-ui';
  import { getRedpackConfig, updateRedpackConfig } from '@/api/redpacket/redpacket';

  const message = useMessage();

  const dynamicNameRule = {
    trigger: ['input', 'blur'],
    required: true,
    validator(rule: unknown, value: string) {
      if (value.length == 0) return new Error('请输入红包名称');
      return true;
    },
  };

  const dynamicMoneyRule = {
    trigger: ['input', 'blur'],
    required: true,
    pattern: /^[0-9]/,
    message: '请输入正确格式的金额',
  };

  const dynamicRoleLevelRule = {
    trigger: ['input', 'blur'],
    required: true,
    pattern: /^[0-9]/,
    message: '请输入正确的等级',
  };

  const formRef: any = ref(null);

  const model = ref({
    dynamicInputValue: [
      { name: '', money: '0', totalRecharge: '0', registTime: '0', roleLevel: '0', isCheck: false },
    ],
  });

  function onCreate() {
    return {
      name: '',
      money: '0',
      totalRecharge: '0',
      registTime: '0',
      roleLevel: '0',
      isCheck: false,
    };
  }

  onMounted(async () => {
    model.value.dynamicInputValue = await getRedpackConfig();
  });

  function formSubmit() {
    // console.log('model.dynamicInputValue');
    // console.log(JSON.stringify(model.value.dynamicInputValue, null, 2));
    formRef.value.validate(async (errors) => {
      if (!errors) {
        await updateRedpackConfig({ config: model.value.dynamicInputValue });
        message.success('保存成功');
      } else {
        message.error('验证失败，请填写完整信息');
      }
    });
  }
</script>
